package com.gitee.chessboard.utils;

import java.util.*;

/**
 * 字符串工具类
 *
 * @author 敲代码的旺财
 * @date 2021/12/7 9:35
 */
public class StringUtils {
    public static String replace(String inString, String oldPattern, String newPattern) {
        if ((inString == null || inString.isEmpty())
                || (oldPattern == null || oldPattern.isEmpty())
                || newPattern == null) {
            return inString;
        }
        int index = inString.indexOf(oldPattern);
        if (index == -1) {
            // no occurrence -> can return input as-is
            return inString;
        }

        int capacity = inString.length();
        if (newPattern.length() > oldPattern.length()) {
            capacity += 16;
        }
        StringBuilder sb = new StringBuilder(capacity);

        int pos = 0;  // our position in the old string
        int patLen = oldPattern.length();
        while (index >= 0) {
            sb.append(inString, pos, index);
            sb.append(newPattern);
            pos = index + patLen;
            index = inString.indexOf(oldPattern, pos);
        }

        // append any characters to the right of a match
        sb.append(inString, pos, inString.length());
        return sb.toString();
    }
}
